


#include "dev_4g.h"
#include "platform.h"
#include "cm_time.h"
#include "proto_plat.h"
#include "logfile.h"

#include "uart_printf.h"
#include "user_nv.h"

//#include "bsp_4g.h"
#include "system.h"
 #include "ota_api.h"
#include "simple_event.h"



// void system_reset(void* param)
// {
//    // cm_pm_reboot();
//      SystemReboot( );
// }





void system_ota_upgrade(void* param)
{
    logfile_write(1,"\n---ota---");

    cm_ota_upgrade();

}

void system_change_server(void* param)
{
    hcat1.network_state=network_ready;
    memset(&hplat_comm, 0, sizeof(plat_comm_t));
}


void elec_threshold_save_event(void* param)
{
  //  elec_threshold_save();
}

void simple_event_init(void)
{
    LOG_NAME();
    
   // simple_event_reg(event_reset,system_reset,NULL);
    simple_event_reg(event_ota,system_ota_upgrade,NULL);
    simple_event_reg(event_change_server,system_change_server,NULL);
    simple_event_reg(event_save_threshold,elec_threshold_save_event,NULL);
}
        

/**************************************************************************************************** */
static simple_event_t simple_event={0};


/**
 * @brief 注册事件回调
 * 
 * @param event 
 * @param cb 
 */
void simple_event_reg(simple_event_enum event, pfunc cb, void* param)
{
    simple_event.cb[event]=cb;
    simple_event.param[event]=param;
}



/**
 * @brief 不管发送多少次，只执行一次
 * 
 * @param event 
 */
void simple_event_send(simple_event_enum event, uint32_t delay_ms)
{
    if(delay_ms)
    {
        simple_event.time_base = get_runtime( );
        simple_event.delay = delay_ms;
    }
    simple_event.event |= 1<<event;
}

static void simple_event_clear(simple_event_enum event)
{
    simple_event.event &= ~(1<<event);
}

static inline uint8_t simple_event_get(simple_event_enum event)
{
    return (simple_event.event & (1<<event)) ? 1:0;
}

/**
 * @brief 事件处理
 * 
 */
void simple_event_handle(void)
{
    if(!simple_event.event)return;

  // printf("%s\n",__FUNCTION__);
    LOG_NAME();


    for(uint8_t i=0;i<event_max;i++)
    {
        if(simple_event_get(i))
        {
            if(simple_event.delay)
            {
                if(time_intval(simple_event.time_base) < simple_event.delay){
                    continue;
                }
            }

            if(simple_event.cb[i]){
                simple_event.cb[i](simple_event.param[i]);
                simple_event_clear(i);
            }
        }
    }
}